/**
 * @format
 * @Author: TC
 * @Date: 2022-03-04 18:01:32
 * @Last Modified by: TC
 * @Last Modified time: 2025-06-12 20:12:54
 */

import { _decorator, EventKeyboard, Input, input } from "cc";
import { app } from "db://assets/FrameWork/App";
import { EFrameEventConst } from "db://assets/FrameWork/Const/FrameEventConst";
import { nsCmdConst } from "db://assets/FrameWork/Module/InputCmd/CmdConst";
import { gameDataMgr } from "../../_Common/Manager/GameDataManager";
import { EntityBase } from "./EntityBase";
const { ccclass, property } = _decorator;

@ccclass("EntityHero")
export class EntityHero extends EntityBase {
    init(): void {
        super.init();
        gameDataMgr.entityHero = this;

        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
        app.eventMgr.register(EFrameEventConst.VIRTUAL_JOY_STICK_BEGIN, this._onVirtualBegin, this);
        app.eventMgr.register(EFrameEventConst.VIRTUAL_JOY_STICK_ANGLE, this._onVirtual, this);
        app.eventMgr.register(EFrameEventConst.VIRTUAL_JOY_STICK_CANEL, this._onVirtualCancel, this);

        gameDataMgr.mainCamera.nodeTarget = this.node;
    }

    protected addUIEvent(): void {
        super.addUIEvent();
    }

    public release(): void {
        super.release();
        gameDataMgr.entityHero = null;
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.off(Input.EventType.KEY_UP, this.onKeyUp, this);
        app.eventMgr.unregister(EFrameEventConst.VIRTUAL_JOY_STICK_BEGIN, this);
        app.eventMgr.unregister(EFrameEventConst.VIRTUAL_JOY_STICK_ANGLE, this);
        app.eventMgr.unregister(EFrameEventConst.VIRTUAL_JOY_STICK_CANEL, this);
    }

    /**
     * 键盘按下事件
     * @param e
     */
    private onKeyDown(e: EventKeyboard): void {
        this.cmd.rdKey[e.keyCode] = true;
    }

    /**
     * 键盘抬起事件
     * @param e
     */
    private onKeyUp(e: EventKeyboard): void {
        this.cmd.rdKey[e.keyCode] = false;
    }

    private _onVirtualBegin(): void {
        // this.keyboard.onKeyDown(nsCmdConst.EKeyboardCode.LEFT);
        // this.cmd.angle = 0;
    }

    private _tempAngle = 10000;
    private _onVirtual(angle: number): void {
        // if (angle == this._tempAngle) return;
        this.keyboard.onKeyDown(nsCmdConst.EKeyboardCode.MOVE, angle);
    }

    private _onVirtualCancel(): void {
        this.keyboard.onKeyUp(nsCmdConst.EKeyboardCode.MOVE);
    }
}
